<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-03-22
// +—————————————————————————————————————————————————————————————————————

    /* curl get请求 */
    function curl_get($url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	} 
    /* curl POST 请求 */
	function curl_post($url,$curlPost=''){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
        if($curlPost){
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        }
        
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
		
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
    /* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
        $checkstr=trim($checkstr);
		$checkstr=urldecode($checkstr);

		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}

		$str=htmlspecialchars($str);

		return $str;	
	}
    
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}
    
    /* 校验签名 */
    function checkSign($data,$sign){
        //return 1;
        if($sign==''){
            return 0;
        }
        $key=DI()->config->get('app.sign_key');
        $str='';
        ksort($data);
        foreach($data as $k=>$v){
            $str.=$k.'='.$v.'&';
        }
        $str.=$key;
        $newsign=md5($str);
        
        if($sign==$newsign){
            return 1;
        }
        return 0;
    }
    
    /* 检验手机号 */
	function checkMobile($mobile,$country_code){
		
		$configpri=getConfigPri();  //当后台开启国际/港澳验证码时, 返回验证通过
		if($configpri['sendcode_type']=='2' && $country_code=='86'){
			return 1001;
		}else if($configpri['sendcode_type']=='1' && $country_code!='86'){
			return 1002;
		}else if($configpri['sendcode_type']=='2'){
			return 1;
		}
		
		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		
		if($ismobile){
			return 1;
		}
        
        return 0;
		
	}
    
    /* 检测用户是否存在 */
    function checkUser($where){
        if($where==''){
            return 0;
        }

        $isexist=DI()->notorm->user->where($where)->fetchOne();
        if($isexist){
            return 1;
        }
        
        return 0;
    }
    
    /* ip限定 */
	function ip_limit(){
		$configpri=getConfigPri();
		if($configpri['iplimit_switch']==0){
			return 0;
		}
		$date = date("Ymd");
		$ip= ip2long($_SERVER["REMOTE_ADDR"]) ; 
		
		$isexist=DI()->notorm->getcode_limit_ip
				->select('ip,date,times')
				->where(' ip=? ',$ip) 
				->fetchOne();
		if(!$isexist){
			$data=array(
				"ip" => $ip,
				"date" => $date,
				"times" => 1,
			);
			$isexist=DI()->notorm->getcode_limit_ip->insert($data);
			return 0;
		}elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
			return 1;
		}else{
			if($date == $isexist['date']){
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('times'=> new NotORM_Literal("times + 1 ")));
				return 0;
			}else{
				$isexist=DI()->notorm->getcode_limit_ip
						->where(' ip=? ',$ip) 
						->update(array('date'=> $date ,'times'=>1));
				return 0;
			}
		}	
	}
    
    /* XML转数组 */
    function xml_to_array($xml){
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
		return $arr;
	}
    
    /* 随机数 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
    
	
	
	/* 发送验证码 */
    function sendCode($account,$code,$country=''){
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		$config = getConfigPri();
        if(!$config['sendcode_switch']){
            $rs['code']=667;
			$rs['msg']='123456';
            return $rs;
        }
		if($config['code_switch']=='2'){ //腾讯云
		
			
			$res=sendCodeTxySms($account,$code,$country);
		}else{ //阿里云
			$res=sendCodeAlySms($account,$code,$country);
		}
		
        //$res=sendEmailCode($account,$code);
        
        return $res;
    }

	/* 发送验证码 -- 阿里云 ------国内外配置 */
	function sendCodeAlySms($mobile,$code,$country=''){		
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        require_once API_ROOT.'/../sdk/aliyunsms/AliSmsApi.php';
		
		$config = getConfigPri();
		$aly_signName=$config['aly_signName'];
		$aly_templateCode=$config['aly_templateCode'];
		
		if($config['sendcode_type']=='2'){ //国际港澳台短信
			$mobile=$country.$mobile;
			
			$aly_signName=$config['aly_signName_inter'];
			$aly_templateCode=$config['aly_templateCode_inter'];
		}
		

		$config  = array(
			'accessKeyId' => $config['aly_keydi'], 
			'accessKeySecret' => $config['aly_secret'], 
			'PhoneNumbers' => $mobile, 
			'SignName' => $aly_signName, 
			'TemplateCode' => $aly_templateCode, 
			'TemplateParam' => array("code"=>$code) 
		);
		
		$go = new AliSmsApi($config);
		$result = $go->send_sms();
		
		
		

		if($result == NULL) {
            $rs['code']=1002;
			$rs['msg']="获取失败";
            return $rs;
         }
		 
         if($result['Code']!='OK') {
            //TODO 添加错误处理逻辑
            $rs['code']=1002;
			//$rs['msg']=$result['Code'];
			$rs['msg']="获取失败";
            return $rs;
         }
	
		$content=$code;
        setSendcode(array('type'=>'1','account'=>$mobile,'content'=>$content));
		
       return $rs;

	}
    
	
	
	
	/* 发送验证码 -- 腾讯云 ------国内外配置 */
	function sendCodeTxySms($mobile,$code,$country=''){
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		require_once API_ROOT."/../sdk/tencentSms/index.php";
		$rs=array();
		$config = getConfigPri();
        
        $appid=$config['tencent_sms_appid'];
        $appkey=$config['tencent_sms_appkey'];
		$smsSign = '';

		
		$smsSign=$config['tencent_sms_signName'];
		$templateId = $config['tencent_sms_templateCode'];
		if($config['sendcode_type']=='2'){ //国际港澳台短信
			$smsSign = $config['tencent_sms_hw_signName'];
			$templateId = $config['tencent_sms_hw_templateCode'];
		}

		$sender = new \Qcloud\Sms\SmsSingleSender($appid,$appkey);

		$params = [$code]; //参数列表与腾讯云后台创建模板时加的参数列表保持一致
		$result = $sender->sendWithParam($country, $mobile, $templateId, $params, $smsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
			
		
		file_put_contents(API_ROOT.'/../data/sendCode_tencent_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
		$arr=json_decode($result,TRUE);

		if($arr['result']==0 && $arr['errmsg']=='OK'){

			$rs['code']=0;
		}else{
			$rs['code']=1002;
			$rs['msg']=$arr['errmsg'];
			//$rs['msg']='验证码发送失败';
		} 
		
		
		$content=$code;
        setSendcode(array('type'=>'1','account'=>$mobile,'content'=>$content));
		return $rs;		
				
	}
	
    /* 验证码记录 */
    function setSendcode($data){
        if($data){
            $data['addtime']=time();
            DI()->notorm->sendcode->insert($data);
        }
    }
    
    /* 密码加密 */
	function setPass($pass){
		$authcode='AEXdfGlE3NCtS35QyN';
		$pass="###".md5(md5($authcode.$pass));
		return $pass;
	}
    
    /* 公共配置 */
	function getConfigPub() {
		$key='getConfigPub';
		$config=hGetAll($key);
		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='site_info'")
					->fetchOne();
            $config=json_decode($config['option_value'],true);
			hMSet($key,$config);
		}

		return 	$config;
	}		
	
	/* 私密配置 */
	function getConfigPri() {
		$key='getConfigPri';
		$config=hGetAll($key);
		if(!$config){
			$config= DI()->notorm->option
					->select('option_value')
					->where("option_name='configpri'")
					->fetchOne();
            $config=json_decode($config['option_value'],true);
			hMSet($key,$config);
		}
        
        if(is_array($config['login_type'])){
            
        }else if($config['login_type']){
            $config['login_type']=preg_split('/,|，/',$config['login_type']);
        }else{
            $config['login_type']=array();
        }
        
        if(is_array($config['share_type'])){
            
        }else if($config['share_type']){
            $config['share_type']=preg_split('/,|，/',$config['share_type']);
        }else{
            $config['share_type']=array();
        }


        
		return 	$config;
	}
    /* 会员等级 */
	function getLevelList(){
        $key='level';
		$level=getcaches($key);
		if(!$level){
			$level=DI()->notorm->level
					->select("*")
					->order("level asc")
					->fetchAll();
            foreach($level as $k=>$v){
                $v['thumb']=get_upload_path($v['thumb']);
                $level[$k]=$v;
            }
			setcaches($key,$level);
		}
        
        return $level;
    }
	function getLevel($exp=0){
        if($exp==0){
            return '1';
        }
		$level=1;
        $level_a=1;
        $level_up=1;
		$list=getLevelList();

		foreach($list as $k=>$v){
			if( $v['level_up']>=$exp){
				$level=$v['level'];
				$level_up=$v['level_up'];
				break;
			}else{
				$level_a = $v['level'];
			}
		}

		//获取等级总数量
		$count=count($list);
		//获取list最后一个元素
		$newlevel=$list[$count-1];
		if($exp==$level_up){  //当这两个值相当时, 返回最大值
			$level =$level;
		}else{
			if($level_a==$newlevel['level']){
				$level=$level_a;
			}else{
				$level = $level < $level_a ? $level:$level_a;
			}			
		}
		return (string)$level;
	}

    /* 主播等级 */
	function getLevelanchorList(){
        $key='level_anchor';
		$level=getcaches($key);
		if(!$level){
			$level=DI()->notorm->level_anchor
					->select("*")
					->order("level asc")
					->fetchAll();
            foreach($level as $k=>$v){
                $v['thumb']=get_upload_path($v['thumb']);
                $level[$k]=$v;
            }
			setcaches($key,$level);			 
		}
        
        return $level;
    }
	function getLevelanchor($exp=0){
        if($exp==0){
            return '1';
        }
		$level=1;
        $level_a=1;
        $level_up=1;
		$list=getLevelanchorList();
		

		foreach($list as $k=>$v){
			if( $v['level_up']>=$exp){
				$level=$v['level'];
				$level_up=$v['level_up'];
				break;
			}else{
				$level_a = $v['level'];
			}
		}
		

		//获取等级总数量
		$count=count($list);
		//获取list最后一个元素
		$newlevel=$list[$count-1];
		if($exp==$level_up){  //当这两个值相当时, 返回最大值
			$level =$level;
		}else{
			if($level_a==$newlevel['level']){
				$level=$level_a;
			}else{
				$level = $level < $level_a ? $level:$level_a;
			}			
		}
		return (string)$level;
	}
	
    
 	/**
	 * 返回带协议的域名
	 */
	function get_host(){
		$config=getConfigPub();
		return $config['site_url'];
	}	
	
	/**
	 * 转化数据库保存的文件路径，为可以访问的url
	 */
	function get_upload_path($file){
		
		
		
        if($file==''){
            return $file;
        }
		if(strpos($file,"http")===0){
            $filepath= $file;
		}else if(strpos($file,"/")===0){
			$filepath= get_host().$file;
		}else{

			$fileinfo=explode("_",$file);
			//上传云存储标识：qiniu：七牛云；aws：亚马逊
			$length=strlen($fileinfo[0])+1;
            if($fileinfo[0]=='qiniu'){
                 // 七牛上传 
                $space_host= DI()->config->get('app.Qiniu.space_host');
				$file=substr($file,$length);
            }else if($fileinfo[0]=='aws'){
                 // 亚马逊上传 
				$space_host= DI()->config->get('app.Aws.space_host');
				$file=substr($file,$length);
            }else{
				$space_host=DI()->config->get('app.Qiniu.space_host');
                // 本地 上传
                // $space_host= get_host().'/upload';
            }
			
			$filepath=$space_host."/".$file;
			
		}
        
        
        return html_entity_decode($filepath);
	}   
	/* 判断token */
	function checkToken($uid,$token) {
        if($uid<1 || $token==''){
            return 700;
        }
        
        $key="token_".$uid;
		$userinfo=hGetAll($key);

		if(!$userinfo){
			$userinfo=DI()->notorm->user_token
						->select('token,expire_time')
						->where('user_id = ? ', $uid)
						->fetchOne();
            if($userinfo){
                hMSet($key,$userinfo);
            }
		}


		if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){
			return 700;				
		}

        
        return 	0;				
		
	}	
	
	/* 用户基本信息 */
	function getUserInfo($uid,$type=0) {
		$info=hGetAll("userinfo_".$uid);
		$info=false;
		if(!$info){
			$info=DI()->notorm->user
					->select('id,user_nickname,avatar,avatar_thumb,sex,signature,consumption,votestotal,birthday,goodnums,badnums,online,isvideo,isvoice,isdisturb,voice_value,video_value,is_firstlogin')
					->where('id=? and user_type="2"',$uid)
					->fetchOne();	
			if($info){
				$info['avatar']=get_upload_path($info['avatar']);
				$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
			}else if($type==1){
                return 	$info;
                
            }else{
                $info['id']=$uid;
                $info['user_nickname']='用户不存在';
                $info['avatar']=get_upload_path('/default.png');
                $info['avatar_thumb']=get_upload_path('/default_thumb.png');
                $info['sex']='0';
                $info['signature']='';
                $info['consumption']='0';
                $info['votestotal']='0';
                $info['birthday']='';
                $info['goodnums']='0';
                $info['badnums']='0';
                $info['isvideo']='0';
                $info['isvoice']='0';
                $info['isdisturb']='0';
                $info['voice_value']='0';
                $info['video_value']='0';
                $info['online']='0';
                $info['is_firstlogin']='0';
            }
            if($info){
                hMSet("userinfo_".$uid,$info);
            }
		}
        
        if($info){
            $info['level']=getLevel($info['consumption']);
            $info['level_anchor']=getLevelanchor($info['votestotal']);
            /* $info['level_anchor']=getLevelanchor($info['goodnums'],$info['badnums']); */

            unset($info['consumption']);
            unset($info['votestotal']);
            unset($info['goodnums']);
            unset($info['badnums']);
        }

		return 	$info;		
	}
    
    /* 统计 关注 */
	function getFollows($uid) {
		$count=DI()->notorm->user_attention
				->where('uid=? ',$uid)
				->count();
		return (string)$count;
	}			
	
	/* 统计 粉丝 */
	function getFans($uid) {
		$count=DI()->notorm->user_attention
				->where('touid=? ',$uid)
				->count();
		return 	(string)$count;
	}
    
    /* 判断是否关注 */
	function isAttention($uid,$touid) {
		$isexist=DI()->notorm->user_attention
					->select("uid")
					->where('uid=? and touid=?',$uid,$touid)
					->fetchOne();
		if($isexist){
			return  '1';
		}
        return  '0';
	}
    
    
    /* 腾讯IM签名-HMAC-SHA256 */
    function setSig($id){
		$sig='';
		$configpri=getConfigPri();
		$appid=$configpri['im_sdkappid'];
		$key=$configpri['im_key'];

        $path= API_ROOT.'/../sdk/txim/';
        require_once( $path ."TLSSigAPIv2.php");
        $api = new \Tencent\TLSSigAPIv2($appid,$key);
        $sig = $api->genSig($id);

        
		return $sig;		
	}

    /* 腾讯IM REST API */
    function getTxRestApi(){
		$configpri=getConfigPri();
		$sdkappid=$configpri['im_sdkappid'];
		$identifier=$configpri['im_admin'];
	
        $sig=setSig($identifier);
        
        $path= API_ROOT.'/../sdk/txim/';
        require_once( $path."restapi/TimRestApi.php");
        
        $api = createRestAPI();
        $api->init($sdkappid, $identifier);
			//托管模式
        $ret = $api->set_user_sig($sig);
        
        if($ret == false){
            file_put_contents(API_ROOT.'/../log/RESTAPI.txt',date('y-m-d H:i:s').'提交参数信息 :'.'设置管理员usrsig失败'."\r\n",FILE_APPEND);
        }
        
        return $api;
	}
    
    /* 扣费 */
    function upCoin($uid,$total=0,$type=0){
        if($uid < 1 || $total<=0){
            return 0;
        }
        if($type==1){
            $ifok =DI()->notorm->user
                    ->where('id = ? and coin >=?', $uid,$total)
                    ->update(array('coin' => new NotORM_Literal("coin - {$total}") ) );
            
            return $ifok;            
        }
        $ifok =DI()->notorm->user
				->where('id = ? and coin >=?', $uid,$total)
				->update(array('coin' => new NotORM_Literal("coin - {$total}"),'consumption' => new NotORM_Literal("consumption + {$total}") ) );
        if($ifok){
            $key='userinfo_'.$uid;
            hIncrByFloat($key,'consumption',$total);
        }
        return $ifok;
    }
    
    /* 增加映票 */
    function addVotes($uid,$votes=0,$votestotal=0){
        
        if($uid < 1 || $votes<=0){
            return 0;
        }
        
        if(!$votestotal){
            $ifok=DI()->notorm->user
					->where('id = ?', $uid)
					->update( array('votes' => new NotORM_Literal("votes + {$votes}") ));
            return $ifok;
        }
        
        $ifok=DI()->notorm->user
					->where('id = ?', $uid)
					->update( array('votes' => new NotORM_Literal("votes + {$votes}"),'votestotal' => new NotORM_Literal("votestotal + {$votestotal}") ));
        if($ifok){
            $key='userinfo_'.$uid;
            hIncrByFloat($key,'votestotal',$votestotal);
        }
        return $ifok;
    }

    /* 扣除映票 */
    function reduceVotes($uid,$votes=0,$votestotal=0,$type=0){
        
        if($uid < 1 || $votes<=0){
            return 0;
        }
        
        if(!$votestotal){
            $ifok=DI()->notorm->user
					->where('id = ? and votes>=?', $uid,$votes)
					->update( array('votes' => new NotORM_Literal("votes - {$votes}") ));
            return $ifok;
        }

        if($type==0){
        	$ifok=DI()->notorm->user
					->where('id = ? and votes>=? and votestotal>?', $uid,$votes,$votestotal)
					->update( array('votes' => new NotORM_Literal("votes - {$votes}"),'votestotal' => new NotORM_Literal("votestotal - {$votestotal}") ));
        }
        
        

		if($type==1){
			$ifok=DI()->notorm->user
					->where('id = ? and votes>=? ', $uid,$votes)
					->update( array('votes' => new NotORM_Literal("votes - {$votes}") ));
		}

        if($ifok){
            $key='userinfo_'.$uid;
            hIncrByFloat($key,'votestotal',-$votestotal);
        }
        return $ifok;
    }
    
    /* 消费记录 */
    function addCoinRecord($insert){
        if($insert){
            $rs=DI()->notorm->user_coinrecord->insert($insert);
        }
        
        return $rs;
    }

    /* 合并消费记录 用于有间隔的消费场景 如：计时扣费 */
    function mergeCoinRecord($insert){
        if($insert){
            $rs=DI()->notorm->user_coinrecord
					->where('type = ? and action = ? and uid = ? and touid = ? and actionid =? and showid =? ', $insert['type'],$insert['action'],$insert['uid'],$insert['touid'],$insert['actionid'],$insert['showid'])
					->update( array('nums' => new NotORM_Literal("nums + {$insert['nums']}"),'totalcoin' => new NotORM_Literal("totalcoin + {$insert['totalcoin']}") ));
            if(!$rs){
                $rs=DI()->notorm->user_coinrecord->insert($insert);
            }
        }
        
        return $rs;
    }
    
    /* 获取用户最新余额、累计消费 */
    function getUserCoin($uid){
        $info =DI()->notorm->user
				->select('consumption,coin')
				->where('id = ?', $uid)
				->fetchOne();	
        return $info;
    }
    
    /* 判断用户是否实名认证 */
    function isAuth($uid){
        $info =DI()->notorm->user_auth
				->select('status')
				->where('uid = ?', $uid)
				->fetchOne();
        if($info && $info['status']==1){
            return '1';
        }
        
        return '0';
    }


    /* 判断用户是否主播认证 */
    function isAuthorAuth($uid){
        $info =DI()->notorm->author_auth
				->select('status')
				->where('uid = ?', $uid)
				->fetchOne();
        if($info && $info['status']==1){
            return '1';
        }
        
        return '0';
    }
    
    /* 判断用户实名认证状态 */
    function getAuthStatus($uid){
        $info =DI()->notorm->user_auth
				->select('status')
				->where('uid = ?', $uid)
				->fetchOne();
        return $info;
    }

    function getAuthorStatus($uid){
        $info =DI()->notorm->author_auth
				->select('status')
				->where('uid = ?', $uid)
				->fetchOne();
        return $info;
    }
    
	/* 离线时间 */
	function offtime($time){
		$cha=time()-$time;
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
		if($cha<60){
			//return $cha.'秒之前';
			return '1分钟之前';
		}else if($iz<60){
			return $iz.'分钟之前';
		}else if($hz<24){
			return $hz.'小时之前';
		}else if($dz<30){
			return $dz.'天之前';
		}else{
			return '30天之前';
		}
	}	
    
    /* 时长 */
	function getLength($cha,$type=0){
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
        if($type==1){
            if($s<10){
                $s='0'.$s;
            }
            if($i<10){
                $i='0'.$i;
            }

            if($h<10){
                $h='0'.$h;
            }
            
            if($hz<10){
                $hz='0'.$hz;
            }
            return $hz.':'.$i.':'.$s;
        }
        
        
		if($cha<60){
			return $cha.'秒';
		}else if($iz<60){
			return $iz.'分'.$s.'秒';
		}else if($hz<24){
			return $hz.'小时'.$i.'分'.$s.'秒';
		}else if($dz<30){
			return $dz.'天'.$h.'小时'.$i.'分'.$s.'秒';
		}
	}	   
    
	/**
	*  @desc 腾讯云推拉流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function PrivateKey_tx($host,$stream,$type){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		$stream_a=explode('_',$stream);
		$streamKey = $stream_a[0];
		$ext = $stream_a[1];
	
		$live_code = $stream;      	
		$now_time = time() + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($push_url_key . $live_code . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;		

		if($type==1){
			//$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" .  $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url;	可录像
			$url = "rtmp://{$push}/live/" . $live_code . $safe_url;	
		}else{
            if($host=='rtmp'){
                $url = "rtmp://{$pull}/live/" . $live_code . $safe_url .'&bizid='.$bizid;
            }else{
                $url = "http://{$pull}/live/" . $live_code . ".flv";
            }
			
		}
		
		return $url;
	}
    
    
    /**
	*  @desc 腾讯云低延迟播流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function tx_acc($host,$stream,$type=0){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$tx_acc_key=$configpri['tx_acc_key'];
		$push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		
		
		/* $stream_a=explode('_',$stream);
		$streamKey = $stream_a[0];
		$ext = $stream_a[1]; 
	
		$live_code = $stream;  */  

		
		$now_time = time();
		$now_time = $now_time + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($tx_acc_key . $stream . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;	
		

        $url = "rtmp://{$pull}/live/" . $stream . $safe_url. '&bizid='.$bizid;
        
		return $url;
	}
	
    
    /* 数字格式化 */
	function NumberFormat($num){
		if($num<10000){

		}else if($num<1000000){
			$num=round($num/10000,2).'万';
		}else if($num<100000000){
			$num=round($num/10000,1).'万';
		}else if($num<10000000000){
			$num=round($num/100000000,2).'亿';
		}else{
			$num=round($num/100000000,1).'亿';
		}
		return $num;
	}
    
	 /* 时间差计算 */
	function datetime($time){
		$cha=time()-$time;
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
		if($cha<60){
			return $cha.'秒前';
		}else if($iz<60){
			return $iz.'分钟前';
		}else if($hz<24){
			return $hz.'小时前';
		}else if($dz<30){
			return $dz.'天前';
		}else{
			return date("Y-m-d",$time);
		}
	}
    
    
    //判断用户是否注销
	function checkIsDestroyByLogin($map,$type){
		
		/* $type 1手机号  0用户id*/
		
		$where="id={$map}";
		if($type==1){
			$where="user_login={$map}";
		}
		
		$info=DI()->notorm->user
			->select('user_status')
			->where($where)
			->fetchOne();
		
		if($info['user_status']==3){
			return 1;
		}

		return 0;
	}

	//html特殊字符转义
	function htmlSpecialCharsDecode($checkstr){
		$checkstr=trim($checkstr);
		$checkstr=urldecode($checkstr);
		if(!$checkstr){
			return $checkstr;
		}

		$str=htmlspecialchars_decode($checkstr);
		return $str;
	}

	//判断一下字段是否在敏感词库内
	function checkSensitiveWords($str){

		//判断用户昵称中是否有敏感词
        $configpri=getConfigPri();
        $sensitive_words=$configpri['sensitive_words'];
        $sensitive_words_arr=explode(',', $sensitive_words);

        if(in_array($str, $sensitive_words_arr)){
        	
            return 1;
        }

        $has_words=0;

        foreach ($sensitive_words_arr as $k => $v) {
        	if(strpos($str, $v)!==false){
        		$has_words=1;
        		break;
        	}
        }

        if($has_words){
        	
            return 1;
        }

        return 0;
	}

	//敏感词替换
	function changeSensitiveWords($str){

		$configpri=getConfigPri();
        $sensitive_words=$configpri['sensitive_words'];
        $sensitive_words_arr=explode(',', $sensitive_words);

        $str_length=mb_strlen($str);

        if(in_array($str, $sensitive_words_arr)){
        	for ($i=0; $i <$str_length ; $i++) { 
        		$new_str.='*';
        	}

        	return $new_str;
        }

        $str_pos=0;
        $xing_str='';

        foreach ($sensitive_words_arr as $k => $v) {
        	$str_pos=strpos($str, $v);
        	if($str_pos!==false){
        		$xing_str='';
        		for ($i=0; $i <mb_strlen($v) ; $i++) { 
        			$xing_str.='*';
        		}
        		
        		$str=str_replace($v,$xing_str,$str);
        	}
        }

        return $str;

        
	}

	/* 消费记录 */
    function addVoteRecord($data){

        if($data){
            $rs=DI()->notorm->user_voterecord->insert($data);
            
        }

        return $rs;
    }

    //映票记录
    function mergeVoteRecord($data){
    	if($data){
    		$rs=DI()->notorm->user_voterecord
					->where('type = ? and action = ? and uid = ? and fromid = ? and actionid =? and showid =? ', $data['type'],$data['action'],$data['uid'],$data['fromid'],$data['actionid'],$data['showid'])
					->update(
						array(
							'nums' => new NotORM_Literal("nums + {$data['nums']}"),
							'total' => new NotORM_Literal("total + {$data['total']}"),
							'votes' => new NotORM_Literal("votes + {$data['votes']}")
						)
					);

            if(!$rs){
                $rs=DI()->notorm->user_voterecord->insert($data);
            }

            return $rs;
    	}
    }

    /**
	 * 判断是否为合法的身份证号码
	 * @param $mobile
	 * @return int
	 */
	function isCreditNo($vStr){

		
		$vCity = array(
		  	'11','12','13','14','15','21','22',
		  	'23','31','32','33','34','35','36',
		  	'37','41','42','43','44','45','46',
		  	'50','51','52','53','54','61','62',
		  	'63','64','65','71','81','82','91'
		);
		
		if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
		 	return false;
		}

	 	if (!in_array(substr($vStr, 0, 2), $vCity)){
	 		return false;
	 	}
	 
	 	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	 	$vLength = strlen($vStr);

	 	if($vLength == 18){
	  		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	 	}else{
	  		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	 	}

		if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday){
		 	return false;
		}

	 	if ($vLength == 18) {
	  		$vSum = 0;
	  		for ($i = 17 ; $i >= 0 ; $i--) {
	   			$vSubStr = substr($vStr, 17 - $i, 1);
	   			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
	  		}
	  		if($vSum % 11 != 1){
	  			return false;
	  		}
	 	}

	 	return true;
	}


    
    